
import UIKit

let kSystemVersion      =   (UIDevice.currentDevice().systemVersion as NSString).doubleValue
let IOS_6               =   kSystemVersion >= 6
let IOS_7               =   kSystemVersion >= 7
let IOS_8               =   kSystemVersion >= 8
let IOS_9               =   kSystemVersion >= 9
let IOS_10              =   kSystemVersion >= 10

let kMainScreen         =  UIScreen.mainScreen()
let ScreenBounds        =  kMainScreen.bounds
let ScreenSize          =  ScreenBounds.size
let ScreenScale         =  kMainScreen.scale
let ScreenHeight        =  ScreenSize.height
let ScreenWidth         =  ScreenSize.width


let ApplicationDelegate =  UIApplication.sharedApplication().delegate

let  fileManger =  NSFileManager.defaultManager()

let myGray:UIColor      =   RGB(0.80, g: 0.80, b: 0.80)
let myTextGray:UIColor  =   RGB(0.54, g: 0.54, b: 0.54)


func RGB(r:Float, g:Float, b:Float, a:Float = 1.0) -> UIColor {
    return UIColor(colorLiteralRed: r/255.0, green: g/255.0, blue: b/255.0, alpha: a < 1.0 ? a: 1.0)
}

func hexString(str:String, a: Float = 1.0) -> UIColor {
    
    let cStrg:NSString = (str as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
    
    if cStrg .hasPrefix("#") {
        cStrg.substringFromIndex(1)
    }
    
    if cStrg.length != 6 {
        return UIColor.blackColor()
    }
    
    var rang: NSRange = NSMakeRange(0, 0)
    rang.location = 0
    rang.length   = 2
    
    let rString   = cStrg.substringWithRange(rang)
    rang.location = 2
    let gString   = cStrg.substringWithRange(rang)
    rang.location = 4
    let bString   = cStrg.substringWithRange(rang)
    
    var  r:UInt32 = 0
    var  g:UInt32 = 0
    var  b:UInt32 = 0
    NSScanner(string: rString).scanHexInt(&r)
    NSScanner(string: gString).scanHexInt(&g)
    NSScanner(string: bString).scanHexInt(&b)
    
    return RGB(Float(r)  , g: Float(g), b: Float(b), a: a)
}

func delay(data: Double, callFunc: ()->()) {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_FOREVER, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
        callFunc()
    })
}

/// 兼容图片
///
/// - parameter path:  文件路径
/// - parameter isA3x: isA3x  是否是@3x 原图

func generateSuitImages(path: String, isA3x: Bool = false) {
    dispatch_async(dispatch_get_global_queue(0, 0)) { 
        
    let newPath: NSString = path.stringByAppendingString("/newImages")
    var isDir: ObjCBool = ObjCBool(false)
    if  (fileManger.fileExistsAtPath(path, isDirectory: &isDir) == false) || isDir.boolValue == false {
        print("path error")
        return
    }
    guard createDirectory(newPath as String) else {
        return
    }
    
    let direnum = fileManger.enumeratorAtPath(path)
    
    let files = NSMutableArray(capacity: 10)
    
    while let fileName = direnum?.nextObject() {
        if ((fileName as! NSString).pathExtension as NSString).isEqualToString("png") {
            files.addObject(fileName)
        }
    }
    
    for nm in files {
        var imgName = nm as! String
        if let rang = imgName.rangeOfString(".png") {
            imgName.removeRange(rang)
        }
        let imgPath = (path as NSString).stringByAppendingPathComponent(imgName)
        let toPath = newPath.stringByAppendingPathComponent(imgName)
//        saveResizedImage(imgPath, toPath: (toPath + ".png"   ), multiple: CGFloat(isA3x ? 0.5   : 0.334))
//        saveResizedImage(imgPath, toPath: (toPath + "@2x.png"), multiple: CGFloat(isA3x ? 0.667 : 1.0))
//        saveResizedImage(imgPath, toPath: (toPath + "@3x.png"), multiple: CGFloat(isA3x ? 1.0   : 1.5))
        
        saveResizedImage(imgPath, toPath: (toPath + ".png"   ), multiple: 1)
        saveResizedImage(imgPath, toPath: (toPath + "@2x.png"), multiple: 2)
        saveResizedImage(imgPath, toPath: (toPath + "@3x.png"), multiple: 3)
    }
  }
}


    // MARK: Extension
extension UIView {
    
    public var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            var r = self.frame
            r.origin.x = newValue
            self.frame = r
        }
    }
    
    public var y: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            var r = self.frame
            r.origin.y = newValue
            self.frame = r
        }
    }
    /// 右边界的x值
    public var rightX: CGFloat {
        get {
            return self.x + self.width
        }
        set {
            var r = self.frame
            r.origin.x = newValue - frame.size.width
            self.frame = r
        }
    }
    /// 下边界的y值
    public var bottomY: CGFloat {
        get {
            return self.y + self.height
        }
        set {
            var r = self.frame
            r.origin.y = newValue - frame.size.height
            self.frame = r
        }
    }
    
    public var centerX : CGFloat {
        get {
            return self.center.x
        }
        set {
            self.center = CGPoint(x: newValue, y: self.center.y)
        }
    }
    
    public var centerY : CGFloat {
        get {
            return self.center.y
        }
        set {
            self.center = CGPoint(x: self.center.x, y: newValue)
        }
    }
    
    public var width: CGFloat{
        get {
            return self.frame.size.width
        }
        set {
            var r = self.frame
            r.size.width = newValue
            self.frame = r
        }
    }
    
    public var height: CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            var r = self.frame
            r.size.height = newValue
            self.frame = r
        }
    }
    
    public var origin: CGPoint {
        get {
            return self.frame.origin
        }
        set {
            self.x = newValue.x
            self.y = newValue.y
        }
    }
    
    public var size: CGSize {
        get {
            return self.frame.size
        }
        set {
            self.width = newValue.width
            self.height = newValue.height
        }
    }
    
    convenience init(backColor: UIColor) {
        self.init()
        backgroundColor = backColor
    }
}

extension UIImage {
    ///压缩图片至目标尺寸
    func compress(with: CGFloat) -> UIImage {
        
        let newH = (with / self.size.width ) * self.size.height
        UIGraphicsBeginImageContext(CGSize(width: with, height: newH))
        self.drawInRect(CGRect(x: 0, y: 0, width: with, height: newH))
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
    
    // MARK: - 降低质量
    func resetSizeOfImageData(source_image: UIImage, maxSize: Int) -> NSData {
        //先调整分辨率
        var newSize = CGSizeMake(source_image.size.width, source_image.size.height)
        
        let tempHeight = newSize.height / 1024
        let tempWidth  = newSize.width / 1024
        
        if tempWidth > 1.0 && tempWidth > tempHeight {
            newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth)
        }
        else if tempHeight > 1.0 && tempWidth < tempHeight {
            newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight)
        }
        
        UIGraphicsBeginImageContext(newSize)
        source_image.drawAsPatternInRect(CGRectMake(0,0,newSize.width,newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        //先判断当前质量是否满足要求，不满足再进行压缩
        var finallImageData = UIImageJPEGRepresentation(newImage,1.0)
        let sizeOrigin      = Int64((finallImageData?.length)!)
        let sizeOriginKB    = Int(sizeOrigin / 1024)
        if sizeOriginKB <= maxSize {
            return finallImageData!
        }
        
        //保存压缩系数
        let compressionQualityArr = NSMutableArray()
        let avg = CGFloat(1.0/250)
        var value = avg
        
        var i = 250
        
        while i >= 1 {
            value = CGFloat(i)*avg
            compressionQualityArr.addObject(value)
            i -= 1
        }
       
        
        //调整大小
        //说明：压缩系数数组compressionQualityArr是从大到小存储。
        //思路：折半计算，如果中间压缩系数仍然降不到目标值maxSize，则从后半部分开始寻找压缩系数；反之从前半部分寻找压缩系数
        finallImageData = UIImageJPEGRepresentation(newImage, CGFloat(compressionQualityArr[125] as! NSNumber))
        if Int(Int64((UIImageJPEGRepresentation(newImage, CGFloat(compressionQualityArr[125] as! NSNumber))?.length)!)/1024) > maxSize {
            //从后半部分开始
            for idx in 126..<250 {
                let value = compressionQualityArr[idx]
                let sizeOrigin   = Int64((finallImageData?.length)!)
                let sizeOriginKB = Int(sizeOrigin / 1024)
                print("当前降到的质量：\(sizeOriginKB)")
                if sizeOriginKB > maxSize {
                    print("\(idx)----\(value)")
                    finallImageData = UIImageJPEGRepresentation(newImage, CGFloat(value as! NSNumber))
                } else {
                    break
                }
            }
        } else {
            //从前半部分开始
            for idx in 0..<125 {
                let value = compressionQualityArr[idx]
                let sizeOrigin   = Int64((finallImageData?.length)!)
                let sizeOriginKB = Int(sizeOrigin / 1024)
                print("当前降到的质量：\(sizeOriginKB)")
                if sizeOriginKB > maxSize {
                    print("\(idx)----\(value)")
                    finallImageData = UIImageJPEGRepresentation(newImage, CGFloat(value as! NSNumber))
                } else {
                    break
                }
            }
        }
        return finallImageData!
    }
}

extension NSMutableAttributedString {

    func attriBusedStr(font: CGFloat, range: NSRange, color: UIColor)  {
        addAttribute(NSFontAttributeName, value: font, range: range)
        addAttribute(NSForegroundColorAttributeName, value: color, range: range)
    }
    
}

    // MARK: Private
private func results(isSF: Bool) -> Bool {
    if isSF {
        print("create directory success")
        return true
    }
    print("create directory failure")
    return false
}

private func createDirectory(path: String) -> Bool {
    var isDir: ObjCBool = ObjCBool(false)
    var isDirExist = fileManger.fileExistsAtPath(path, isDirectory: &isDir)
    if (isDir.boolValue == false || isDirExist == false) {
        return results((try? fileManger.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)) != nil)
    }
    isDirExist = fileManger.fileExistsAtPath(path)
    return isDirExist
}

/**
 9 ÷ 16 = 0.5625 的屏幕
 按宽度适配
 321 × 102
 214 68     @1  107  34
 428 × 136  @2  214  68
 642 × 204  @3  321  102
 iPhone4~6(+)的屏幕高宽比：
 4： 分辨率960*640，     高宽比1.5                        320x480
 5： 分辨率1136*640，    高宽比1.775                      320x568
 6： 分辨率1334*750，    高宽比1.779                      375x667
 6p：分辨率1920*1080，   高宽比1.778                      414x736
        (1242x2208->)
 */
private func saveResizedImage(path: String, toPath: String, multiple: CGFloat) {
    
    let img = UIImage(named: path)!
    let size = CGSizeMake(img.size.width * multiple, img.size.height * multiple)
    
    UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
    img.drawInRect(CGRect(origin: CGPointZero, size: size))
    let newImg = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    ((UIImagePNGRepresentation(newImg)?.writeToFile(toPath, atomically: true)) != nil) ?
        print("success --- " + toPath) : print("failure --- " + path)
}
